package cn.xiaolang.function.file_manage;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class PrintStreamDemo {
	public static void main(String[] args) {
		printWriter();
		printWriterAutoFlush();
		readWriterConsole();
	}

	/**
	 * 使用PrintWriter打印到控制台
	 */
	public static void readWriterConsole() {
		BufferedReader bufferedReader = null;
		PrintWriter printWriter = null;
		try {
			bufferedReader = new BufferedReader(new FileReader("samples/a.txt"));
			/**
			 * 实例化printWriter打印对象，并开启自动刷新功能
			 */
			printWriter = new PrintWriter(System.out, true);
			String readerString = null;
			while ((readerString = bufferedReader.readLine()) != null) {
				printWriter.println(readerString);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.err.println("readWriterConsole over!!!");
			if (printWriter != null) {
				printWriter.close();
			}
		}
	}

	/**
	 * 自动刷新的打印流写入到文件
	 * 
	 * @author fuhw/DeanKano
	 */
	public static void printWriterAutoFlush() {
		PrintWriter printWriter = null;
		try {
			/**
			 * 注意，PrintWriter(new Writer,boolean AutoFlsh) 可以设置是否可以自动刷新缓冲区数据
			 * 如果每个参数为String类型，它是没有boolean AutoFlsh参数的，这点要注意
			 */
			printWriter = new PrintWriter(new FileWriter("samples/a.txt"), true);
			printWriter.println("将数据写入到文件:");
			printWriter.println("因为开启了自动刷新功能，所以println相当于以下执行了以下方法");
			printWriter.println("printWriter.write(String string); //写入字符");
			printWriter.println("printWriter.newLine(); //换行");
			printWriter.println("printWriter.flsh(); //清空缓存");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.err.println("printWriterAutoFlush to file successed!!!");
			if (printWriter != null) {
				printWriter.close();
			}
		}
	}

	/**
	 * 使用打印流写入到文件
	 * 
	 * @author fuhw/DeanKano
	 */
	public static void printWriter() {
		// 创建打印流对象
		PrintWriter printWriter = null;
		try {
			printWriter = new PrintWriter("samples/a.txt");
			printWriter.println("将数据写入到文件");
			// 清空缓冲区数据
			printWriter.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			System.err.println("printWriter to file successed!!!");
			if (printWriter != null) {
				printWriter.close();
			}
		}
	}

}
